import { pick } from "lodash-es";
import { Container, Extract, IDestroyOptions } from "pixi.js";
import { DataOfLayer } from "../../Controller/Controller";
import { Canvas } from "../Canvas";
import { PixelFile, LayerPersistData } from "../Data/CanvasFile";
import { hub } from "../hub";
import { Layer } from "./Layer";

export class LayerManager extends Container {
    layers = new Map<string, Layer>();
    /** 纯粹的 Layer 的容器 */
    LayerContainer = new Container();
    user = "Konghayao";
    version = "1.0.0";
    createdAt = new Date().getTime();
    updatedAt = new Date().getTime();
    id = new Date().getTime() + "";
    design: { width: number; height: number; tileSize: number };
    constructor(
        public canvas: Canvas,
        height: number,
        width: number,
        public name: string = "未命名文件"
    ) {
        super();

        this.design = { width, height, tileSize: 64 };
        this.sortableChildren = true;
        hub.on("deleteLayer", this.deleteLayer);
        hub.on("createLayer", this.createLayer);
        this.addChild(this.LayerContainer);
    }

    destroy(options?: boolean | IDestroyOptions): void {
        super.destroy.call(this, options);
        hub.off("deleteLayer", this.deleteLayer);
        hub.off("createLayer", this.createLayer);
        for (let i of this.layers.values()) {
            i.destroy();
        }
    }

    centerAll() {
        const { height, width } = this.canvas.app.screen;
        this.pivot.set(this.width / 2, this.height / 2);
        this.position.set(width / 2, height / 2);
    }
    /** 图层计数器 */
    private layerCounter = 1;
    createLayer = (
        name = "图层 " + this.layerCounter,
        layerData?: LayerPersistData
    ) => {
        const layer = new Layer(
            this.canvas,
            name,
            this.design,
            layerData
        ).mount(this.LayerContainer, this.canvas.cover);
        console.log("创建 ", name);

        layer.zIndex = this.layerCounter;
        this.layers.set(layer.id, layer);
        this.layerCounter++;
        return this;
    };
    deleteLayer = (layer: DataOfLayer) => {
        this.layers.get(layer.id)?.destroy();
        this.layers.delete(layer.id);
    };
    updateAllLayer() {
        for (const layer of this.layers.values()) {
            hub.emit("updateLayer", layer);
        }
    }
    /** 载入文件中获取的对象 */
    loadFile(file: PixelFile) {
        const {
            user,
            version,
            createdAt,
            updatedAt,
            layers,
            height,
            width,
            id,
        } = file;

        Object.assign(this, {
            user,
            id,
            version,
            createdAt,
            updatedAt,
            width: width * this.scale.x,
            height: height * this.scale.x,
        });
        // 销毁内部的 layer 对象
        [...this.layers.values()].forEach((i) => i.destroy());
        this.layers.clear();

        // 创建新的 layer
        layers.forEach((data) => this.createLayer(data.name, data));
        // this.children.forEach((i: any) => i?.resize());
        console.log("载入数据");
    }
    /** 输出整个数据 */
    outputFile(): PixelFile {
        return {
            ...this.design,
            ...pick(this, ["user", "version", "createdAt", "name", "id"]),
            updatedAt: new Date().getTime(),
            layers: [...this.layers.values()]
                .sort((a, b) => {
                    console.log(a.zIndex);
                    return a.zIndex - b.zIndex;
                })
                .map((i) => i._toString()),
        };
    }
    /**输出缩略图文本 */
    outputPreview(rate = 0.8) {
        const extract = this.canvas.app.renderer.plugins.extract as Extract;
        const data = extract.base64(this.LayerContainer, "image/webp", rate);

        return data;
    }
}
